<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2019/3/8
 * Time: 10:33
 */

namespace service\excel\order;
use app\storage\common\AppConstant;
use app\storage\common\Template;
use app\storage\service\MaterielService;
use app\storage\service\SupplierService;
use service\excel\AbstractExcel;
use think\Config;
use think\Db;

class MaterielBom extends AbstractExcel{


    public function __construct()
    {
        parent::__construct();
        $this->config = Config::get('materiel_bom');
    }

    public function getData()
    {
        $reader = $this->phpReader->load($this->path);
        $sheet = $reader->getSheet(0);//获取第一个工作区

        $orderId  = $sheet->getCell($this->config['order_id'])->getValue();
        $this->tableData['orderId']  = empty($orderId) ? create_unique_id('BOM') : $orderId;
        $this->tableData['productType'] = trim($sheet->getCell($this->config['product_type'])->getValue());
        $this->tableData['workshop'] = trim($sheet->getCell($this->config['workshop'])->getValue());
        $this->tableData['supplierId'] = trim($sheet->getCell($this->config['supplier_id'])->getValue());
        $this->tableData['storageName'] = trim($sheet->getCell($this->config['storage'])->getValue());
        $this->tableData['remark'] = trim($sheet->getCell($this->config['remark'])->getValue());


        $highestColumn = $sheet->getHighestRow(); //取得总行数，为接下里获取数据准备

        for ($i = $this->config['data_begin']; $i <= $highestColumn; $i++) {//从配置中读书数据从哪行开始读取数据
            $materielId = trim($sheet->getCell($this->config['sub_materiel_id'] . $i)->getValue());
            $count = trim($sheet->getCell($this->config['count'] . $i)->getValue());
            if (empty($materielId)) {//防止空行，如果取不到数据了就跳出
                break;
            }
            $fentryid = trim($sheet->getCell($this->config['fentryid'] . $i)->getValue());
            $this->tableData['materiel'][] = [
                'sub_materiel_id' => strtoupper($materielId),
                'count' => $count,
                'fentryid' => empty($fentryid)?'':$fentryid,
            ];
        }
        array_values($this->tableData['materiel']);
    }

    public function checkData()
    {
        $this->getData();
        $this->storageUuid = Db::table('iwh_storage')->where(['name' => $this->tableData['storageName']])->value('uuid');
        if (empty($this->storageUuid)) {
            return ret_template(false, "仓库{$this->tableData['storageName']}不存在");
        }
        $materiel = $this->tableData['materiel'];
        $supplierId = $this->tableData['supplierId'];
        $subMaterielCode = array_unique(array_column($materiel, 'sub_materiel_id'));
        $materielInfo = MaterielService::create_materiel($subMaterielCode);
        $supplierInfo = SupplierService::create_supplier($supplierId);
        if ($materielInfo['success'] === false) {
            return $materielInfo;
        }
        if ($supplierInfo['success'] === false) {
            return $supplierInfo;
        }
        $this->tableData['supplierUuid'] = $supplierInfo['data'][0]['uuid'];
        preg_match('/\w[A-z]+/', $this->tableData['orderId'], $match);//解析开头的字符
        if (!in_array($match[0], $this->config['allow_pre'])) {//判断是不是在允许的开头里面
            return ret_template(false, '出库单号抬头错误');
        }
        $fentryid = array_unique(array_column($this->tableData['materiel'],'fentryid'));
        $where['order_id'] = $this->tableData['orderId'];
        $where['fentryid'] =['in',$fentryid] ;
        $repeat = Db::table('iwh_bom')->where($where)->column('fentryid');
        if (count($repeat)) {
            $repeat = array_intersect($repeat,$fentryid);
            $order = empty($repeat) ? $this->tableData['orderId'] : $this->tableData['orderId'] . ' 行号:' . implode(',',$repeat);
            return ret_template(false, "单号{$order}已存在");
        }
        if(empty($this->tableData['materiel'])){
            return ret_template(false, '请填写出库单物料');
        }
        return ret_template(true,'','');
    }

    public function insertToDb()
    {
        $fentryid = array_unique(array_column($this->tableData['materiel'], 'fentryid'));
        $fentryid = count($fentryid) == 1 && $fentryid[0] == '' ? [0] : $fentryid;
        $count = [];
        foreach ($this->tableData['materiel'] as $item) {
            if (empty($item['fentryid'])) {
                $count[0][$item['sub_materiel_id']] += $item['count'];
            } else {
                $count[$item['fentryid']][$item['sub_materiel_id']] += $item['count'];
            }
        }
        $bom = $bomDetail = [];
        foreach ($fentryid as $item) {
            $bomUuid = create_uuid();
            $fentryid = empty($item)?'':$item;
            $bom[] = Template::bomTemplate($bomUuid, $this->tableData['orderId'], $fentryid, $this->storageUuid, $this->tableData['supplierUuid'],AppConstant::MANUAL_BOM,'',0,'','',$this->tableData['remark']);
            $item = $item === '' ? 0 : $item;
            foreach ($count[$item] as $k => $value) {
                $bomDetail[] = Template::bomDetailTemplate($bomUuid,$k,$value);
            }
        }
        Db::startTrans();
        $tranDet  = $tranBom = true;
        if (!empty($bom)) {
            $tranBom = Db::table('iwh_bom')->insertAll($bom);
        }
        if (!empty($bomDetail)) {
            $tranDet = Db::table('iwh_bom_detail')->insertAll($bomDetail);
        }
        if ($tranBom && $tranDet) {
            Db::commit();
            return ret_template(true, '上传成功');
        } else {
            Db::rollback();
            return ret_template(false, '上传失败');
        }
    }
}